package com.sptus.framework.mapper.util;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.SecureRandom;

/**
 * @Author zhongdl
 * @Date 2024/5/27 18:46
 * @Description: SSL工具类
 */
public class SslUtil {


    /**
     * @Description
     * @param: trustStorePath  truststore.jks文件路径
     * @param: trustStorePassword truststore.jks生成时密码
     * @param: keyStorePath keystore.jks文件路径
     * @param: keyStorePassword keystore.jks生成时密码
     * @Author zhongdl
     * @Date 2024/5/27 18:46
     */
    public static SSLSocketFactory getSocketFactory(final InputStream trustStorePath, final String trustStorePassword, final InputStream    keyStorePath, final String keyStorePassword) throws Exception {
        // 加载信任库
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(trustStorePath, trustStorePassword.toCharArray());

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);

        // 加载密钥库
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(keyStorePath, keyStorePassword.toCharArray());

        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(keyStore, keyStorePassword.toCharArray());

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());

        return sslContext.getSocketFactory();
    }

}

